package com.smart.es;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.es.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.DocumentOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;

import javax.annotation.Resource;

/**
 * 索引 Index 操作
 * 数据操作
 * 增
 * 删
 * 改
 * <p>
 * 查
 * 多条键查询
 * 分页查询
 */
@SpringBootTest
@Slf4j
public class ProductDaoTest1 {
    @Resource
    ElasticsearchRestTemplate template;
    @Resource
    ElasticsearchOperations operations;
    @Resource
    ObjectMapper objectMapper;

    @Test
    void testSave() {
        Product product = new Product();
        // 自动创建ID
        product.setProductId(1L);
        product.setTitle("手机");
        Product product1 = template.save(product);
        log.info(product1.toString());
    }

    /**
     * 更新跟添加
     */
    @Test
    void testUpdate() throws JsonProcessingException {
        Product product = new Product();
        // 自动创建ID
        product.setProductId(1L);
        product.setTitle("手机");


        /**
         * 先查询
         */
        // es内部维护的ID
        UpdateQuery query = UpdateQuery.builder("123456")
                // 如果索引存在 则不修改 否则就新增
                .withDocAsUpsert(true)
                .withDocument(Document.parse(objectMapper.writeValueAsString(product)))
                .build();

        UpdateResponse response = template.update(query, operations.getIndexCoordinatesFor(Product.class));
        log.info(response.getResult().toString());


        /**
         * 修改整个文档
         */
        IndexQuery indexQuery = new IndexQueryBuilder()
                .withObject(product)
                .build();
        template.index(indexQuery, operations.getIndexCoordinatesFor(Product.class));

    }


    @Test
    void testDel() {
//        template.delete()
    }
}